/**
 * Utility functions for exporting data
 */
import * as XLSX from 'xlsx';

/**
 * Exports data to Excel file
 * @param data - Array of objects to export
 * @param fileName - Name of the exported file (without extension)
 */
export const exportToExcel = (data: any[], fileName: string = 'export'): void => {
  try {
    // Convert data to worksheet
    const worksheet = XLSX.utils.json_to_sheet(data);
    
    // Create workbook and add the worksheet
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
    
    // Generate file and trigger download
    XLSX.writeFile(workbook, `${fileName}.xlsx`);
  } catch (error) {
    console.error('Export failed:', error);
    // If XLSX is not available, fallback to CSV
    exportToCSV(data, fileName);
  }
};

/**
 * Fallback export to CSV when XLSX is not available
 * @param data - Array of objects to export
 * @param fileName - Name of the exported file (without extension)
 */
const exportToCSV = (data: any[], fileName: string = 'export'): void => {
  try {
    // Get headers from first object
    const headers = Object.keys(data[0] || {});
    
    // Convert data to CSV format
    let csvContent = headers.join(',') + '\n';
    
    data.forEach(item => {
      const row = headers.map(header => {
        // Handle special characters and ensure proper CSV format
        const cell = item[header] === null || item[header] === undefined ? '' : item[header];
        return typeof cell === 'string' ? `"${cell.replace(/"/g, '""')}"` : cell;
      });
      csvContent += row.join(',') + '\n';
    });
    
    // Create and download the file
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    
    link.setAttribute('href', url);
    link.setAttribute('download', `${fileName}.csv`);
    link.style.visibility = 'hidden';
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } catch (error) {
    console.error('CSV export failed:', error);
  }
}; 